package com.zany.children.action;

import com.zany.children.service.ClassService;
import com.zany.children.service.TeacherService;
import com.zany.children.vo.Class;
import com.zany.children.vo.Teacher;
import com.zany.system.vo.UserInfoVO;
import com.zany.util.ZanyErrorMsg;
import com.zany.util.ZanyException;
import com.zany.util.action.AbstractActionSupport;
import com.zany.util.ajax.AjaxTools;
import com.zany.util.json.JSONObject;
import com.zany.util.json.JsonTools;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TeacherAction extends AbstractActionSupport {

    private TeacherService teacherService;

    private ClassService classService;

    public TeacherService getTeacherService() {
        return teacherService;
    }

    public ClassService getClassService() {
        return classService;
    }

    public void setClassService(ClassService classService) {
        this.classService = classService;
    }

    public void setTeacherService(TeacherService teacherService) {
        this.teacherService = teacherService;
    }

    private static Log logger = LogFactory.getLog(TeacherAction.class);

    private Map session;


    public void list() throws ZanyException {
        String start = request.getParameter("start");
        String classId = request.getParameter("classId");
        String name = request.getParameter("name");
        UserInfoVO userInfo = (UserInfoVO) session.get("userInfo");
        response = ServletActionContext.getResponse();
        Integer pageStart = StringUtils.isBlank(start) ? 1 : Integer.parseInt(start);
        Teacher teacher = new Teacher();
        teacher.setPageMessage(pageStart);
        Map<String, Object> map = new HashMap<String, Object>();
        if (userInfo != null) {
            map.put("orgCode", userInfo.getUserOrg());
        }
        map.put("classId", classId);
        map.put("name", name);
        map.put("pageStart", pageStart);
        map.put("pageEnd", teacher.getPageEnd());
        Integer pageTotal = teacherService.getTeacherListPageCount(map);
        List<Teacher> teacherListPage = teacherService.getTeacherListPage(map);
        for (Teacher teacher1 : teacherListPage) {
            List<Class> clazz = teacher1.getClazz();
            StringBuffer classNames = new StringBuffer();
            int i = 0;
            for (Class item : clazz) {
                if (i == clazz.size() - 1) {
                    classNames.append(item.getName());
                } else {
                    classNames.append(item.getName()).append(",");
                }
                i++;
            }
            teacher1.setClassNames(classNames.toString());
        }

        AjaxTools.exAjax("{results:" + pageTotal + ",ZANY:" + JsonTools.lstBeanToJson(teacherListPage) + "}", response);
    }


    public void save() throws ZanyException {
        response = ServletActionContext.getResponse();
        String name = request.getParameter("name");
        String sex = request.getParameter("sex");
        String age = request.getParameter("age");
        String position = request.getParameter("position");
        String seniority = request.getParameter("seniority");
        String tel = request.getParameter("tel");
        String classId = request.getParameter("classId");
        Teacher teacher = new Teacher();
        UserInfoVO userInfo = (UserInfoVO) session.get("userInfo");
        String orgCode = null;
        if (userInfo != null) {
            orgCode = userInfo.getUserOrg();
            teacher.setCreater(userInfo.getUserName());
            teacher.setOrgCode(orgCode);
        }
        teacher.setSex(sex);
        teacher.setName(name);
        teacher.setTel(tel);
        teacher.setPosition(position);
        teacher.setOrgCode(orgCode);
        teacher.setSeniority(seniority);
        teacher.setAge(Integer.valueOf(age));
//        Map<String, Object> map = new HashMap<String, Object>();
//        map.put("name", name);
//        Integer pageTotal = teacherService.getTeacherListPageCount(map);
//        if (pageTotal != 0) {
//            AjaxTools.exAjax("{\"success\":false,msg:\"老师已存在！\"}", this.response);
//        } else {
        teacherService.saveTeacher(teacher, Long.parseLong(classId));
        AjaxTools.exAjax("{success:true}", this.response);
//        }
    }

    public void update() throws ZanyException {
        response = ServletActionContext.getResponse();
        String name = request.getParameter("name");
        String sex = request.getParameter("sex");
        String age = request.getParameter("age");
        String position = request.getParameter("position");
        String seniority = request.getParameter("seniority");
        String tel = request.getParameter("tel");
        String classId = request.getParameter("classId");
        String id = request.getParameter("id");
        Teacher teacher = new Teacher();
        UserInfoVO userInfo = (UserInfoVO) session.get("userInfo");
        String orgCode = null;
        if (userInfo != null) {
            orgCode = userInfo.getUserOrg();
        }
        teacher.setSex(sex);
        teacher.setName(name);
        teacher.setTel(tel);
        teacher.setPosition(position);
        teacher.setOrgCode(orgCode);
        teacher.setSeniority(seniority);
        teacher.setAge(Integer.valueOf(age));
        teacher.setId(Long.parseLong(id));
//        Map<String, Object> map = new HashMap<String, Object>();
//        map.put("name", name);
//        Integer pageTotal = teacherService.getTeacherListPageCount(map);
//        if (pageTotal != 0) {
//            AjaxTools.exAjax("{\"success\":false,msg:\"老师已存在！\"}", response);
//        } else {
        Class clazz = classService.getClassById(Long.parseLong(classId));
        ArrayList<Class> classes = new ArrayList<Class>();
        classes.add(clazz);
        teacher.setClazz(classes);
        teacherService.updateTeacher(teacher);
        AjaxTools.exAjax("{success:true}", response);
    }

    public void delete() throws ZanyException {
        if (logger.isInfoEnabled()) {
            logger.info("TeacherAction.delete()");
        }
        response = ServletActionContext.getResponse();
        String delId[] = request.getParameterValues("delId");
        try {
            if (delId.length > 0) {
                for (int i = 0; i < delId.length; i++) {
                    teacherService.deleteTeacherById(Long.parseLong(delId[i]));
                }
                AjaxTools.exAjax("{success:true}", response);
            }
        } catch (Exception e) {
            AjaxTools.exAjax("{success:false}", response);
            throw new ZanyException(ZanyErrorMsg.ERR_DEFAULT, e.getMessage(), e);
        }
    }

    public void detail() throws ZanyException {
        String id = request.getParameter("id");
        response = ServletActionContext.getResponse();
        Teacher teacher = teacherService.getTeacherById(Long.parseLong(id));
        JSONObject jsonObject = JsonTools.beanToJson(teacher);
        String json = jsonObject.toString();
        AjaxTools.exAjax("{results:" + 1 + ",ZANY:" + json + "}", response);
    }

    @Override
    public void setSession(Map map) {
        this.session = map;
    }
}
